//JavaScript code for refreshing, saving scrollbar positions

function getCookie(name)
{
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if (start == -1) {
        return "0";
    }
    var end = document.cookie.indexOf(";", len);
    if (end == -1) {
        end = document.cookie.length;
    }
    return document.cookie.substring(len, end);
}

var timeoutid = -1;
var timeout_time = 30;//in seconds; should be the same as in the "refresh" meta-tag

function refresh()
{
    document.location.reload(true);       
}

function pageload(name, numTables)
{
    timeoutid = setTimeout( "refresh()", timeout_time*1000 );

    //sets page scrollbar position
    var scrollx = getCookie(name + "_scrollx");
    var scrolly = getCookie(name + "_scrolly");
    document.documentElement.scrollLeft = scrollx;
    document.documentElement.scrollTop = scrolly;
    
    var temp;
    //sets table scrollbar position(s) and SortableManagers for sortable_tables
    for (i = 0; i < numTables; i++) {

	//scrollbar positions
	temp = getCookie(name + "_table" + i + "_scrollx");
	document.getElementById("table" + i).scrollLeft = temp;

	//SortableManagers for sortable_tables
	temp_k = getCookie(name + "_sortable_table" + i + "_col");
	temp_o = getCookie(name + "_sortable_table" + i + "_order");
	sort_managers_array[i] = new SortableManager();
	sort_managers_array[i].sortkey = temp_sort_key;
	sort_managers_array[i].initWithTable('sortable_table' + i);
	if (temp_k != 0) {
	    sort_managers_array[i].drawSortedRows((temp_k-1), (temp_o == "true"), true);
	}
    }
}

function unload(name, numTables)
{
    var expdate = new Date();
    expdate.setSeconds(expdate.getSeconds()+10);

    //saves window scrollbar position
    document.cookie = name + "_scrollx=" + window.pageXOffset + ";expires=" + expdate;
    document.cookie = name + "_scrolly=" + window.pageYOffset + ";expires=" + expdate;

    //saves table scrollbar position; no vertical scroll
    //saves current sorted columns in tables
    for (i = 0; i < numTables; i++) {
	document.cookie = name + "_table" + i + "_scrollx=" + document.getElementById("table" + i).scrollLeft + ";expires=" + expdate;
	document.cookie = name + "_sortable_table" + i + "_col=" + (sort_managers_array[i].sortkey + 1) + ";expires=" + expdate; //use +1 for sortkey so zero can mean to use default
	document.cookie = name + "_sortable_table" + i + "_order=" + sort_managers_array[i].sortState + ";expires=" + expdate;
    }
}

function turnOnRefresh()
{
    timeoutid = setTimeout( "refresh()", timeout_time*1000 );
}    

function turnOffRefresh()
{
    clearTimeout(timeoutid);
}